import {ref, computed, onMounted, watch} from 'vue';
import utilAxios from '@/util/util-axios';

export default function use({ queryParam = {} }, modularOne, modularTwo, rowsWatch = () => {}) {
    let api = utilAxios.initBaseApi(modularOne, modularTwo);

    const rows = ref([]);

    onMounted(() => {
        api.list({ limit: 999, ...queryParam }).then(res => {
            rows.value = res.records;
            // watch(rows, (value) => {
            //     rowsWatch(value);
            // }, { deep: true });
        })
    })

    const remove = (id) => {
        api.remove(id).then(res => {
            rows.value = rows.value.filter(row => row.id !== id);
            rowsWatch(rows.value);
        });
    }

    const add = (newRow) => {
        if (rows.value.find(row => row.id === newRow.id)) {
            return;
        }
        rows.value.push(newRow);
        rowsWatch(rows.value);
    }

    const update = async (obj) => {
        let res = await api.add(obj);
        add(res);
    }

    return {
        rows, remove, update
    }
}